package com.ying.excel.easyexcel;

import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.ying.excel.domain.po.ExecelUser;
import com.ying.excel.service.IExecelUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author liujunjie
 * @Description description
 * @Date 2024-10-10 00:21
 **/
@Slf4j
public class ExcelUserDataListener extends AnalysisEventListener<ExecelUser> {
    private static final int BATCH_COUNT = 100;

    private List<ExecelUser> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public ExcelUserDataListener(IExecelUserService userService) {
        this.userService = userService;
    }

    private IExecelUserService userService;

    @Override
    public void invoke(ExecelUser data, AnalysisContext context) {

        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        System.out.println("cachedDataList: "+cachedDataList);
        userService.saveBatch(cachedDataList);
    }
}
